package com.fub;

import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.fub.guidance.BuildingDAO;
import com.fub.guidance.BuildingVersionDAO;
import com.fub.guidance.RoomDataDAO;
import com.fub.guidance.RoutingGraphDAO;
import com.fub.positioning.ReferencePointDAO;
import com.fub.update.BuildingUpdate;
import com.fub.update.BuildingVersionMap;
import com.fub.update.SDCardReader;
import com.fub.update.UpdateActivity;
import com.fub.update.UpdateService;
import com.fub.util.PreferenceDAO;
import com.fub.util.Util;
import com.fub.view.BasicPreferences;
import com.fub.view.MapActivity;

public class Start extends Activity implements OnClickListener {

	private static final int RESET = 0;
	private static final int SETTINGS = 1;
	private static final float RADIUS_DELTA = 0.0001f;
	private Button btnMapActivity;
	private Button btnUpdate;
	private Button btnChangeBuilding;
	private Button btnBasicSettings;
	private PreferenceDAO preferenceDAO;
	private BuildingVersionDAO buildingVersionsDAO;
	private SDCardReader sdCardReader;
	private AlertDialog ImportFileDialog;
	private AlertDialog changeBuildingDialog;
	public static Bitmap fullBitmap;
	private UpdateService updateService;
	private UpdateService.UpdateServiceBinder updateServiceBinder;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.preferenceDAO = new PreferenceDAO(this);
		this.buildingVersionsDAO = new BuildingVersionDAO(this);
		this.sdCardReader = new SDCardReader(this);
		setContentView(R.layout.main);
		setClickListener();
		checkBuildingVersions();
		Intent intent = getIntent();
		if (intent.getDataString() != null) {
			float[] cooridintes = Util.parseLatitudeAndLongitude(Uri
					.parse(intent.getDataString()));
			startMap(cooridintes[0], cooridintes[1]);
		}
		if (this.preferenceDAO.isAutomaticUpdate()) {
			initUpdateServiceConnection();
		}
	}

	private void initUpdateServiceConnection() {
		Intent intent = new Intent(getApplicationContext(), UpdateService.class);
		bindService(intent, new ServiceConnection() {
			@Override
			public void onServiceDisconnected(ComponentName name) {
			}

			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				updateServiceBinder = (UpdateService.UpdateServiceBinder) service;
				updateService = updateServiceBinder.getService();
				checkForNewUpdates();
			}
		}, BIND_AUTO_CREATE);
	}

	private void checkForNewUpdates() {
		try {
			List<BuildingUpdate> buildingUpdates = updateService.getUpdates();
			for (BuildingUpdate update : buildingUpdates) {
				if (update.getBuildingId().equals(
						new PreferenceDAO(this).getBuildingId())) {
					updateService.updateOrAddNewBuilding(update, this);
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void startMap(float latitude, float longitude) {
		BuildingVersionMap buildingMapLocal = this.buildingVersionsDAO
				.getAllBuildingVersionsMap();
		for (String buildingId : buildingMapLocal.getBuildingsIds()) {
			float buildingLatitude = buildingMapLocal.getLatitude(buildingId);
			float buildingLongitude = buildingMapLocal.getLongitude(buildingId);
			if (Util.isInRadius(RADIUS_DELTA, buildingLatitude,
					buildingLongitude, latitude, longitude)) {
				changeBuilding(buildingId);
				startActivity(new Intent(this, MapActivity.class));
				return;
			}
		}
		startActivity(new Intent(this, UpdateActivity.class));
	}

	private void checkBuildingVersions() {
		if (this.buildingVersionsDAO.getAllLocalBuildingIds().length == 0) {
			showImportORUpdateDialog();
		}
	}

	private void setClickListener() {
		this.btnMapActivity = (Button) findViewById(R.id.btnMapActivity);
		this.btnMapActivity.setOnClickListener(this);
		this.btnChangeBuilding = (Button) findViewById(R.id.btnChangeBuilding);
		this.btnChangeBuilding.setOnClickListener(this);
		this.btnUpdate = (Button) findViewById(R.id.btnUpdate);
		this.btnUpdate.setOnClickListener(this);
		this.btnBasicSettings = (Button) findViewById(R.id.btnBasicSettings);
		this.btnBasicSettings.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v == this.btnMapActivity) {
			startActivity(new Intent(this, MapActivity.class));
		} else if (v == this.btnUpdate) {
			startActivity(new Intent(this, UpdateActivity.class));
		} else if (v == this.btnChangeBuilding) {
			showChangeBuildingDialog();
		} else if (v == this.btnBasicSettings) {
			startActivity(new Intent(this, BasicPreferences.class));
		}
	}

	private void deleteGraphWallsVersions() {
		RoutingGraphDAO nodeEdgeDBService = new RoutingGraphDAO(this);
		nodeEdgeDBService.deleteAllNodes();
		nodeEdgeDBService.deleteAllEdges();
		nodeEdgeDBService.deleteAllRelations();
		new BuildingDAO(this).deleteAllWalls();
		new BuildingVersionDAO(this).deleteAllVersions();
		new RoomDataDAO(this).deleteAllRoomData();
		new ReferencePointDAO(this).deleteAll();
		this.preferenceDAO.setRoutingDisabled();
	}

	private void startUpdateActiviy() {
		startActivity(new Intent(this, UpdateActivity.class));
	}

	private void showImportORUpdateDialog() {
		final CharSequence[] items = {
				getResources().getString(R.string.import_sd),
				getResources().getString(R.string.import_server) };
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getResources().getString(
				R.string.dialog_no_building_in_system));
		builder.setSingleChoiceItems(items, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						if (item == 0) {
							showImportDialog();
						} else if (item == 1) {
							startUpdateActiviy();
						}
						Start.this.changeBuildingDialog.hide();
					}
				});
		this.changeBuildingDialog = builder.create();
		this.changeBuildingDialog.show();
	}

	private void showImportDialog() {
		final CharSequence[] items = this.sdCardReader.getFubFiles().toArray(
				new String[this.sdCardReader.getFubFiles().size()]);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getResources().getString(R.string.select_import_file));
		builder.setSingleChoiceItems(items, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						String fileToImport = items[item].toString();
						String buildingId = fileToImport.split("\\.")[0];
						Start.this.sdCardReader.startAddNewBuildingThread(
								buildingId, fileToImport);
						Start.this.ImportFileDialog.hide();
					}
				});
		this.ImportFileDialog = builder.create();
		this.ImportFileDialog.show();
	}

	private void showChangeBuildingDialog() {
		final CharSequence[] items = new BuildingVersionDAO(this)
				.getAllLocalBuildingIds();
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getResources().getString(R.string.change_building));
		builder.setSingleChoiceItems(items, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						Toast.makeText(getApplicationContext(),
								"Change to " + items[item], Toast.LENGTH_SHORT)
								.show();
						Start.this.changeBuildingDialog.hide();
						changeBuilding(items[item].toString());
						LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);
						layout.getParent().recomputeViewAttributes(layout);
						layout.invalidate();
					}
				});
		this.changeBuildingDialog = builder.create();
		this.changeBuildingDialog.show();
	}

	private void changeBuilding(String buildingId) {
		Start.this.preferenceDAO.setBuildingId(buildingId);
		Start.this.preferenceDAO.setRoutingDisabled();
		Start.this.preferenceDAO.setRoutingStart(PreferenceDAO.NO_NODE_SET);
		Start.this.preferenceDAO.setRoutingEnd(PreferenceDAO.NO_NODE_SET);
		Start.this.preferenceDAO.setSelectedNodeId(PreferenceDAO.NO_NODE_SET);
		initUpdateServiceConnection();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(RESET, RESET, RESET, "Reset");
		menu.add(SETTINGS, SETTINGS, SETTINGS, "Einstellungen");
		return result;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case RESET:
			deleteGraphWallsVersions();
			break;
		case SETTINGS:
			startActivity(new Intent(this, BasicPreferences.class));
			break;
		}
		return super.onOptionsItemSelected(item);
	}
}
